package cn.it62.utils;

import java.util.Scanner;

/**
 * @author zhenhuaShen
 * @version 1.0
 * @date 2019/8/8
 * @description cn.it62.utils
 */
public class Utils {
    public static final Scanner sc = new Scanner(System.in);

    private static Utils utils;
    /**
     * 私有化构造方法，目的不能继承和自己new对象
     */
    private Utils() {
    }

    public static Utils getUtils() {
        if (utils == null) {
            return utils = new Utils();
        }
        return utils;
    }

    /**
     * 输入指定范围在整数的方法
     *
     * @param msg
     * @param start
     * @param end
     * @return
     */
    public int formatInput(String msg, int start, int end) {
        while (true) {
            System.out.print(msg);
            if (sc.hasNextInt()) {
                int num = sc.nextInt();
                if (num <= end && num >= start) {
                    return num;
                }
                System.out.println("输入的数必须在" + start + "-" + end + "范围");
            } else {
                System.out.println("输入范围是" + start + "-" + end + "之间的整数，你输入的是" + sc.next());

            }
        }
    }

    /**
     * 输入指定范围在小数的方法
     *
     * @param msg
     * @param start
     * @param end
     * @return
     */
    public double formatInput(String msg, double start, double end) {
        while (true) {
            System.out.print(msg);
            if (sc.hasNextDouble()) {
                double num = sc.nextDouble();
                if (num <= end && num >= start) {
                    return num;
                }
                System.out.println("取值范围在" + start + "-" + end + "之间");
            } else {
                System.out.println("请输入范围" + start + "-" + end + "之间的整数，你输入的是" + sc.next());

            }
        }
    }

    /**
     * @param msg
     * @param start
     * @param end
     * @return
     * @throws Exception
     */
    public int formatInteger(String msg, int start, int end) throws Exception {
        if (msg == null || msg.equals("")) {
            throw new Exception("输入信息msg不能为null");
        }
        while (true) {
            System.out.println(msg);
            try {
                int num = sc.nextInt();
                if (num > end || num < start) {
                    System.out.println("输入的数必须在" + start + "~" + end + "范围！");
                    continue;
                }
                return num;
            } catch (Exception e) {
                System.out.println("输入整数，你输入的是：" + sc.next());
            }
        }
    }

}
